#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
导出数据库信息到文件
"""

import os
import sys
import django
from datetime import datetime

# 设置Django环境
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'TradingPlatform_Server.settings')
django.setup()

from Server.models import (
    User, Store, Takeout, Menu, Address, 
    Order, Payment, Message, Discuss, Delivery, Kind
)

def export_to_file():
    """导出数据库信息到文件"""
    
    # 生成文件名
    timestamp = datetime.now().strftime('%Y%m%d_%H%M%S')
    filename = '数据库导出_%s.txt' % timestamp
    
    print("\n正在导出数据库信息...")
    print("目标文件: %s\n" % filename)
    
    with open(filename, 'w', encoding='utf-8') as f:
        # 写入标题
        f.write("="*100 + "\n")
        f.write(" " * 35 + "数据库完整信息导出\n")
        f.write(" " * 35 + "导出时间: %s\n" % datetime.now().strftime('%Y-%m-%d %H:%M:%S'))
        f.write("="*100 + "\n\n")
        
        # 统计信息
        f.write("数据统计\n")
        f.write("-"*100 + "\n")
        f.write("用户数量: %d\n" % User.objects.count())
        f.write("店铺数量: %d\n" % Store.objects.count())
        f.write("外卖数量: %d\n" % Takeout.objects.count())
        f.write("订单数量: %d\n" % Order.objects.count())
        f.write("地址数量: %d\n" % Address.objects.count())
        f.write("菜单数量: %d\n" % Menu.objects.count())
        f.write("支付记录: %d\n" % Payment.objects.count())
        f.write("消息数量: %d\n" % Message.objects.count())
        f.write("评论数量: %d\n" % Discuss.objects.count())
        f.write("配送记录: %d\n" % Delivery.objects.count())
        f.write("分类数量: %d\n" % Kind.objects.count())
        f.write("\n\n")
        
        # 用户详细信息
        f.write("="*100 + "\n")
        f.write("用户表详细信息\n")
        f.write("="*100 + "\n\n")
        
        users = User.objects.all()
        for i, user in enumerate(users, 1):
            f.write("用户 #%d\n" % i)
            f.write("  ID: %s\n" % user.id)
            f.write("  手机号: %s\n" % user.phone)
            f.write("  昵称: %s\n" % user.username)
            f.write("  密码: %s\n" % user.password)
            f.write("  余额: %.2f 元\n" % user.money)
            f.write("  是否管理员: %s\n" % ("是" if user.is_admin else "否"))
            f.write("\n")
        
        # 店铺信息
        f.write("\n" + "="*100 + "\n")
        f.write("店铺表详细信息\n")
        f.write("="*100 + "\n\n")
        
        stores = Store.objects.all()
        for i, store in enumerate(stores, 1):
            f.write("店铺 #%d\n" % i)
            f.write("  ID: %s\n" % store.id)
            f.write("  名称: %s\n" % store.name)
            f.write("  电话: %s\n" % store.phone)
            f.write("  所有者ID: %s\n" % store.user_id)
            f.write("  审核状态: %s\n" % ("已通过" if store.is_pass else "待审核"))
            f.write("\n")
        
        # 外卖信息
        f.write("\n" + "="*100 + "\n")
        f.write("外卖表详细信息\n")
        f.write("="*100 + "\n\n")
        
        takeouts = Takeout.objects.all()
        for i, takeout in enumerate(takeouts, 1):
            f.write("外卖 #%d\n" % i)
            f.write("  ID: %s\n" % takeout.id)
            f.write("  名称: %s\n" % takeout.name)
            f.write("  价格: %.2f 元\n" % takeout.price)
            f.write("  店铺ID: %s\n" % takeout.store_id)
            f.write("  审核状态: %s\n" % ("已通过" if takeout.is_pass else "待审核"))
            f.write("\n")
        
        # 订单信息
        f.write("\n" + "="*100 + "\n")
        f.write("订单表详细信息\n")
        f.write("="*100 + "\n\n")
        
        orders = Order.objects.all()
        for i, order in enumerate(orders, 1):
            f.write("订单 #%d\n" % i)
            f.write("  ID: %s\n" % order.id)
            f.write("  用户ID: %s\n" % order.user_id)
            f.write("  外卖ID: %s\n" % order.takeout_id)
            f.write("  数量: %d\n" % order.num)
            f.write("  总价: %.2f 元\n" % order.total_price)
            if hasattr(order, 'create_time'):
                f.write("  创建时间: %s\n" % order.create_time)
            f.write("\n")
        
        f.write("\n" + "="*100 + "\n")
        f.write("导出完成！\n")
        f.write("="*100 + "\n")
    
    print("\n[成功] 数据已导出到: %s" % filename)
    print("\n您可以用文本编辑器打开该文件查看详细信息。\n")
    
    return filename

if __name__ == '__main__':
    try:
        export_to_file()
    except Exception as e:
        print("\n[错误] %s" % str(e))
        import traceback
        traceback.print_exc()

